package com.chang.controller;

import com.chang.entity.Admin;
import com.chang.entity.scale_personality;
import com.chang.service.AdminService;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.apache.commons.fileupload.FileUploadException;


/*
@Controller
public class UploadController {
    @Autowired
    private AdminService adminService;

    private Admin currentAdmin;

    @RequestMapping("/UploadHandleServlet")
    public void upload(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        //得到上传文件的保存目录，将上传的文件存放于WEB-INF目录下，不允许外界直接访问，保证上传文件的安全
        System.out.println("执行了上传文件");
        */
/*String savePath = "G:/workCode/java_idea/new_-java-web/src/main/webapp/FILE";*//*

        String savePath = "D:\\";
        File file = new File(savePath);
        //判断上传文件的保存目录是否存在
        if (!file.exists() && !file.isDirectory()) {
            System.out.println(savePath+"目录不存在，需要创建");
            //创建目录
            file.mkdir();
        }

        //消息提示

        String message = "";
        try {
            //使用Apache文件上传组件处理文件上传步骤：
            //1、创建一个DiskFileItemFactory工厂;将请求消息实体中的每一个项目封装成单独的DiskFileItem (FileItem接口的实现) 对象的任务
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //2、创建一个文件上传解析器
            ServletFileUpload upload = new ServletFileUpload(factory);
            //解决上传文件名的中文乱码
            upload.setHeaderEncoding("UTF-8");
            //3、判断提交上来的数据是否是上传表单的数据  ??
            if (!ServletFileUpload.isMultipartContent(request)) {
                //按照传统方式获取数据
                return;
            }
            //4、使用ServletFileUpload解析器解析上传数据，解析结果返回的是一个List<FileItem>集合，每一个FileItem对应一个Form表单的输入项
            List<FileItem> list = upload.parseRequest(request);
            for (FileItem item : list) {
                //如果fileitem中封装的是普通输入项的数据
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    //解决普通输入项的数据的中文乱码问题
                    String value = item.getString("UTF-8");
                    //value = new String(value.getBytes("iso8859-1"),"UTF-8");
                    System.out.println(name + "=" + value);
                } else {//如果fileitem中封装的是上传文件
                    //得到上传的文件名称，
                    String filename = item.getName();
                    System.out.println(filename);
                    if (filename == null || filename.trim().equals("")) {
                        continue;
                    }
                    //注意：不同的浏览器提交的文件名是不一样的，有些浏览器提交上来的文件名是带有路径的，如：  c:\a\b\1.txt，而有些只是单纯的文件名，如：1.txt
                    //处理获取到的上传文件的文件名的路径部分，只保留文件名部分
                    //  需不需要将 "\\" 改成File.separator

                    filename = filename.substring(filename.lastIndexOf("\\") + 1);
                    //获取item中的上传文件的输入流
                    InputStream in = item.getInputStream();


                    //创建一个文件输出流
                    FileOutputStream out = new FileOutputStream(savePath + "\\" + filename);
                    //创建一个缓冲区
                    byte buffer[] = new byte[1024];
                    //判断输入流中的数据是否已经读完的标识
                    int len = 0;
                    //循环将输入流读入到缓冲区当中，(len=in.read(buffer))>0就表示in里面还有数据
                    while ((len = in.read(buffer)) > 0) {
                        //使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
                        out.write(buffer, 0, len);
                    }
                    in.close();
                }
            }




            for (FileItem item : list) {
                InputStream in = item.getInputStream();
                Workbook workbook = WorkbookFactory.create(in);
                //获取工作表
                Sheet sheet = workbook.getSheetAt(0);
                //获取总行
                int rows = sheet.getPhysicalNumberOfRows();
                System.out.println(rows);
                if(rows>2){
                    //获取单元格
                    for(int i=1;i<rows-2;i++){
                        Row row=sheet.getRow(i);
                        scale_personality s1 = new scale_personality();

                        String Name = row.getCell(0).getStringCellValue();
                        s1.setName(Name);
                        try {
                            String optionA = row.getCell(1).getStringCellValue();
                            s1.setOptionA(optionA);
                        } catch (IllegalStateException e) {
                            double optionA=row.getCell(1).getNumericCellValue();
                            s1.setOptionA(String.valueOf(optionA));
                        }
                        try {
                            String optionB = row.getCell(2).getStringCellValue();
                            s1.setOptionB(optionB);
                        } catch (IllegalStateException e) {
                            double optionB=row.getCell(2).getNumericCellValue();
                            s1.setOptionB(String.valueOf(optionB));
                        }

                        try {
                            String optionC = row.getCell(3).getStringCellValue();
                            s1.setOptionC(optionC);
                        } catch (IllegalStateException e) {
                            double optionC=row.getCell(3).getNumericCellValue();
                            s1.setOptionC(String.valueOf(optionC));
                        }

                        try {
                            String optionD = row.getCell(4).getStringCellValue();
                            s1.setOptionD(optionD);
                        } catch (IllegalStateException e) {
                            double optionD=row.getCell(4).getNumericCellValue();
                            s1.setOptionD(String.valueOf(optionD));
                        }

                        try {
                            String optionE = row.getCell(5).getStringCellValue();
                            s1.setOptionE(optionE);
                        } catch (IllegalStateException e) {
                            double optionE=row.getCell(5).getNumericCellValue();
                            s1.setOptionE(String.valueOf(optionE));
                        }

                        try {
                            String optionF = row.getCell(6).getStringCellValue();
                            s1.setOptionF(optionF);
                        } catch (IllegalStateException e) {
                            double optionF=row.getCell(6).getNumericCellValue();
                            s1.setOptionF(String.valueOf(optionF));
                        }

                        int A_score = (int)row.getCell(7).getNumericCellValue();
                        s1.setA_score(A_score);
                        int B_score = (int)row.getCell(8).getNumericCellValue();
                        s1.setB_score(B_score);
                        int C_score = (int)row.getCell(9).getNumericCellValue();
                        s1.setC_score(C_score);
                        int D_score = (int)row.getCell(10).getNumericCellValue();
                        s1.setD_score(C_score);
                        int E_score = (int)row.getCell(11).getNumericCellValue();
                        s1.setE_score(E_score);
                        int F_score = (int)row.getCell(12).getNumericCellValue();
                        s1.setF_score(F_score);
                        int type_text = (int)row.getCell(13).getNumericCellValue();
                        s1.setType_text(type_text);
                        System.out.println(F_score+" "+type_text);
                        adminService.addScaleProblem(s1);
                    }
                }


                item.delete();

                message = "文件上传成功！";
            }

        }
        catch (Exception e) {
                    message= "文件上传失败！";
                    e.printStackTrace();

                }
        request.setAttribute("message",message);
        request.getRequestDispatcher("message").forward(request, response);
    */
/*return "message";*//*

    }

}
*/

@Controller
public class UploadController {
    @Autowired
    private AdminService adminService;

    private Admin currentAdmin;


    @RequestMapping("/UploadHandleServlet")
    public void upload(@RequestParam("file1") MultipartFile file, HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {

        //消息提示
        String message = "";
        //文件类型判断
        String fileName = file.getOriginalFilename();
       /* if (!fileName.endsWith(".xls") || !fileName.endsWith(".xlsx")) {
            message = "文件类型错误";
            request.setAttribute("message", message);
            request.getRequestDispatcher("message").forward(request, response);
        }*/
        String savePath = "/usr/local/DaChuang/tests/";
        //String savePath = "G:\\";
        File saveFile = new File(savePath);

        //判断上传文件的保存目录是否存在
        if (!saveFile.exists() && !saveFile.isDirectory()) {
            System.out.println(savePath + "目录不存在，正在创建");
            //创建目录
            saveFile.mkdir();
        }

        try {
            //获取真正文件名
            fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
            File excelFile = new File(savePath + fileName);
            if (excelFile.exists()) {
                excelFile.delete();
            }
            file.transferTo(excelFile);

            //使用Apache文件上传组件处理文件上传步骤：
            //1、创建一个DiskFileItemFactory工厂;将请求消息实体中的每一个项目封装成单独的DiskFileItem (FileItem接口的实现) 对象的任务
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //2、创建一个文件上传解析器
            ServletFileUpload upload = new ServletFileUpload(factory);
            //解决上传文件名的中文乱码
            upload.setHeaderEncoding("UTF-8");
            //3、判断提交上来的数据是否是上传表单的数据  ??
            if (!ServletFileUpload.isMultipartContent(request)) {
                //按照传统方式获取数据
                return;
            }
            //4、使用ServletFileUpload解析器解析上传数据，解析结果返回的是一个List<FileItem>集合，每一个FileItem对应一个Form表单的输入项

                InputStream in = file.getInputStream();
                Workbook workbook = null;
                try {
                    workbook = WorkbookFactory.create(in);
                } catch (InvalidFormatException e) {
                    e.printStackTrace();
                }
                //获取工作表
                Sheet sheet = workbook.getSheetAt(0);
                //获取总行
                int rows = sheet.getPhysicalNumberOfRows();
                System.out.println(rows);
                if (rows > 2) {
                    //获取单元格
                    for (int i = 1; i < rows - 2; i++) {
                        Row row = sheet.getRow(i);
                        scale_personality s1 = new scale_personality();

                        String Name = row.getCell(0).getStringCellValue();
                        s1.setName(Name);
                        try {
                            String optionA = row.getCell(1).getStringCellValue();
                            s1.setOptionA(optionA);
                        } catch (IllegalStateException e) {
                            double optionA = row.getCell(1).getNumericCellValue();
                            s1.setOptionA(String.valueOf(optionA));
                        }
                        try {
                            String optionB = row.getCell(2).getStringCellValue();
                            s1.setOptionB(optionB);
                        } catch (IllegalStateException e) {
                            double optionB = row.getCell(2).getNumericCellValue();
                            s1.setOptionB(String.valueOf(optionB));
                        }

                        try {
                            String optionC = row.getCell(3).getStringCellValue();
                            s1.setOptionC(optionC);
                        } catch (IllegalStateException e) {
                            double optionC = row.getCell(3).getNumericCellValue();
                            s1.setOptionC(String.valueOf(optionC));
                        }

                        try {
                            String optionD = row.getCell(4).getStringCellValue();
                            s1.setOptionD(optionD);
                        } catch (IllegalStateException e) {
                            double optionD = row.getCell(4).getNumericCellValue();
                            s1.setOptionD(String.valueOf(optionD));
                        }

                        try {
                            String optionE = row.getCell(5).getStringCellValue();
                            s1.setOptionE(optionE);
                        } catch (IllegalStateException e) {
                            double optionE = row.getCell(5).getNumericCellValue();
                            s1.setOptionE(String.valueOf(optionE));
                        }

                        try {
                            String optionF = row.getCell(6).getStringCellValue();
                            s1.setOptionF(optionF);
                        } catch (IllegalStateException e) {
                            double optionF = row.getCell(6).getNumericCellValue();
                            s1.setOptionF(String.valueOf(optionF));
                        }

                        int A_score = (int) row.getCell(7).getNumericCellValue();
                        s1.setA_score(A_score);
                        int B_score = (int) row.getCell(8).getNumericCellValue();
                        s1.setB_score(B_score);
                        int C_score = (int) row.getCell(9).getNumericCellValue();
                        s1.setC_score(C_score);
                        int D_score = (int) row.getCell(10).getNumericCellValue();
                        s1.setD_score(D_score);
                        int E_score = (int) row.getCell(11).getNumericCellValue();
                        s1.setE_score(E_score);
                        int F_score = (int) row.getCell(12).getNumericCellValue();
                        s1.setF_score(F_score);
                        int type_text = (int) row.getCell(13).getNumericCellValue();
                        s1.setType_text(type_text);
                        System.out.println(F_score + " " + type_text);
                        adminService.addScaleProblem(s1);

                }

                message = "文件上传成功！";
            }
        }
        catch(Exception e){
                message = "文件上传失败！";
                e.printStackTrace();
            }
            request.setAttribute("message", message);
            request.getRequestDispatcher("message").forward(request, response);
    }
}